/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.comut.crud.bo;

import com.comut.crud.pojo.FindAndSet;
import com.comut.crud.dao.SubgroupDao;
import com.comut.crud.ejb.interfaces.ISubgroupAction;
import com.comut.crud.pojo.subgroup.Subgroup;
import com.comut.crud.util.ParseJson;
import com.comut.lib.error.ErrorCodes;
import com.comut.lib.exception.JSONMalFormedException;
import com.comut.lib.exception.ObjectFoundException;
import com.comut.lib.exception.ObjectNotFoundException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;

/**
 *
 * @author asantos
 */
public class SubgroupHandler implements ISubgroupAction {

    private static Logger _logger = Logger.getLogger(SubgroupHandler.class.getName());
    private Connection _connection;
    private SubgroupDao subgroupDao;

    public SubgroupHandler(Connection connection) {
        this._connection = connection;
        subgroupDao = new SubgroupDao(_connection);

    }

    public Subgroup insertSubgroup(Subgroup subgroup) throws ObjectFoundException {
        if(subgroup.isValid()){
            int id = subgroupDao.createSubgroup(subgroup);
            Subgroup toRet = new Subgroup();
            toRet.setId(id);
            _logger.info(toRet.toString());
            return toRet;
        }
        else
            throw new JSONMalFormedException("The mandatory attributes are not in json.",ErrorCodes.JSON_MAL_FORMED);
    }

    public void deleteSubgroup(Subgroup subgroup) throws ObjectNotFoundException {
        _logger.info(subgroup.toString());
        subgroupDao.deleteSubgroup(subgroup.getId());
    }

    public void updateSubgroup(String subgroup) throws ObjectNotFoundException {
        _logger.info(subgroup.toString());
        //check if the BasicDBObject is well formed
        FindAndSet fas = ParseJson.getInstance().buildSQLQuery(subgroup, ParseJson.getInstance().getSubgroupFind(), ParseJson.getInstance().getSubgroupUpdate(),
                ParseJson.getInstance().getSubgroupFindStr(), ParseJson.getInstance().getSubgroupUpdateStr());
        //update the subgroup
        subgroupDao.updateSubgroup(fas);
    }

    public Subgroup getSubgroup(Subgroup subgroup) throws ObjectNotFoundException {
        
        ResultSet rs = subgroupDao.getSubgroup(subgroup.getId());
        Subgroup toRet = new Subgroup();
        try {
            if (rs.next()) {
                toRet.setId(subgroup.getId());
                toRet.setAlias(rs.getString("alias"));
            }
        } catch (SQLException ex) {
            _logger.error(ex);
        }
        return toRet;
    }
    
}
